<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>SQL | Zhang Shuo'blog</title><meta name="keywords" content="SQL"><meta name="author" content="Zhang Shuo"><meta name="copyright" content="Zhang Shuo"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、基础 二、创建表 三、修改表 四、插入 五、更新 六、删除 七、查询 DISTINCT LIMIT   八、排序 九、过滤 十、通配符 十一、计算字段 十二、函数 汇总 文本处理 日期和时间处理 数值处理   十三、分组 十四、子查询 十五、连接 内连接 自连接 自然连接 外连接   十六、组合查询 十七、视图 十八、存储过程 十九、游标 二十、触发器 二十一、事务管理 二十二、字符集 二">
<meta property="og:type" content="article">
<meta property="og:title" content="SQL">
<meta property="og:url" content="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/SQL/index.html">
<meta property="og:site_name" content="Zhang Shuo&#39;blog">
<meta property="og:description" content="一、基础 二、创建表 三、修改表 四、插入 五、更新 六、删除 七、查询 DISTINCT LIMIT   八、排序 九、过滤 十、通配符 十一、计算字段 十二、函数 汇总 文本处理 日期和时间处理 数值处理   十三、分组 十四、子查询 十五、连接 内连接 自连接 自然连接 外连接   十六、组合查询 十七、视图 十八、存储过程 十九、游标 二十、触发器 二十一、事务管理 二十二、字符集 二">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/20.jpg">
<meta property="article:published_time" content="2021-12-06T09:36:00.000Z">
<meta property="article:modified_time" content="2021-12-10T13:10:43.103Z">
<meta property="article:author" content="Zhang Shuo">
<meta property="article:tag" content="SQL">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://zhang-shuo-fr.gitee.io/hexo3/img/20.jpg"><link rel="shortcut icon" href="/hexo3/img/mao_tou_xiang.jpg"><link rel="canonical" href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/SQL/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//fonts.googleapis.com" crossorigin=""/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="manifest" href="/hexo3/pwa/manifest.json"/><link rel="apple-touch-icon" sizes="180x180" href="/hexo3/pwa/apple-touch-icon.png"/><link rel="icon" type="image/png" sizes="32x32" href="/hexo3/pwa/32.png"/><link rel="icon" type="image/png" sizes="16x16" href="/hexo3/pwa/16.png"/><link rel="mask-icon" href="/hexo3/pwa/safari-pinned-tab.svg" color="#5bbad5"/><link rel="stylesheet" href="/hexo3/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Titillium+Web&amp;display=swap" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/hexo3/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: true,
    post: true
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'SQL',
  isPost: true,
  isHome: false,
  isHighlightShrink: undefined,
  isToc: true,
  postUpdate: '2021-12-10 21:10:43'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    document.addEventListener('pjax:complete', detectApple)})(window)</script><style type="text/css">#toggle-sidebar {left:100px}</style><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/hexo3/img/mao_tou_xiang.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/archives/"><div class="headline">文章</div><div class="length-num">176</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/tags/"><div class="headline">标签</div><div class="length-num">45</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/hexo3/categories/"><div class="headline">分类</div><div class="length-num">15</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/hexo3/img/20.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/hexo3/">Zhang Shuo'blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/hexo3/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 小窝</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/hexo3/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/hexo3/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/hexo3/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/hexo3/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/hexo3/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">SQL</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-12-06T09:36:00.000Z" title="发表于 2021-12-06 17:36:00">2021-12-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-12-10T13:10:43.103Z" title="更新于 2021-12-10 21:10:43">2021-12-10</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/hexo3/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/">数据库</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">4.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>14分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="SQL"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><!-- GFM-TOC -->
<ul>
<li><a href="#%E4%B8%80%E5%9F%BA%E7%A1%80">一、基础</a></li>
<li><a href="#%E4%BA%8C%E5%88%9B%E5%BB%BA%E8%A1%A8">二、创建表</a></li>
<li><a href="#%E4%B8%89%E4%BF%AE%E6%94%B9%E8%A1%A8">三、修改表</a></li>
<li><a href="#%E5%9B%9B%E6%8F%92%E5%85%A5">四、插入</a></li>
<li><a href="#%E4%BA%94%E6%9B%B4%E6%96%B0">五、更新</a></li>
<li><a href="#%E5%85%AD%E5%88%A0%E9%99%A4">六、删除</a></li>
<li><a href="#%E4%B8%83%E6%9F%A5%E8%AF%A2">七、查询</a><ul>
<li><a href="#distinct">DISTINCT</a></li>
<li><a href="#limit">LIMIT</a></li>
</ul>
</li>
<li><a href="#%E5%85%AB%E6%8E%92%E5%BA%8F">八、排序</a></li>
<li><a href="#%E4%B9%9D%E8%BF%87%E6%BB%A4">九、过滤</a></li>
<li><a href="#%E5%8D%81%E9%80%9A%E9%85%8D%E7%AC%A6">十、通配符</a></li>
<li><a href="#%E5%8D%81%E4%B8%80%E8%AE%A1%E7%AE%97%E5%AD%97%E6%AE%B5">十一、计算字段</a></li>
<li><a href="#%E5%8D%81%E4%BA%8C%E5%87%BD%E6%95%B0">十二、函数</a><ul>
<li><a href="#%E6%B1%87%E6%80%BB">汇总</a></li>
<li><a href="#%E6%96%87%E6%9C%AC%E5%A4%84%E7%90%86">文本处理</a></li>
<li><a href="#%E6%97%A5%E6%9C%9F%E5%92%8C%E6%97%B6%E9%97%B4%E5%A4%84%E7%90%86">日期和时间处理</a></li>
<li><a href="#%E6%95%B0%E5%80%BC%E5%A4%84%E7%90%86">数值处理</a></li>
</ul>
</li>
<li><a href="#%E5%8D%81%E4%B8%89%E5%88%86%E7%BB%84">十三、分组</a></li>
<li><a href="#%E5%8D%81%E5%9B%9B%E5%AD%90%E6%9F%A5%E8%AF%A2">十四、子查询</a></li>
<li><a href="#%E5%8D%81%E4%BA%94%E8%BF%9E%E6%8E%A5">十五、连接</a><ul>
<li><a href="#%E5%86%85%E8%BF%9E%E6%8E%A5">内连接</a></li>
<li><a href="#%E8%87%AA%E8%BF%9E%E6%8E%A5">自连接</a></li>
<li><a href="#%E8%87%AA%E7%84%B6%E8%BF%9E%E6%8E%A5">自然连接</a></li>
<li><a href="#%E5%A4%96%E8%BF%9E%E6%8E%A5">外连接</a></li>
</ul>
</li>
<li><a href="#%E5%8D%81%E5%85%AD%E7%BB%84%E5%90%88%E6%9F%A5%E8%AF%A2">十六、组合查询</a></li>
<li><a href="#%E5%8D%81%E4%B8%83%E8%A7%86%E5%9B%BE">十七、视图</a></li>
<li><a href="#%E5%8D%81%E5%85%AB%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B">十八、存储过程</a></li>
<li><a href="#%E5%8D%81%E4%B9%9D%E6%B8%B8%E6%A0%87">十九、游标</a></li>
<li><a href="#%E4%BA%8C%E5%8D%81%E8%A7%A6%E5%8F%91%E5%99%A8">二十、触发器</a></li>
<li><a href="#%E4%BA%8C%E5%8D%81%E4%B8%80%E4%BA%8B%E5%8A%A1%E7%AE%A1%E7%90%86">二十一、事务管理</a></li>
<li><a href="#%E4%BA%8C%E5%8D%81%E4%BA%8C%E5%AD%97%E7%AC%A6%E9%9B%86">二十二、字符集</a></li>
<li><a href="#%E4%BA%8C%E5%8D%81%E4%B8%89%E6%9D%83%E9%99%90%E7%AE%A1%E7%90%86">二十三、权限管理</a></li>
<li><a href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99">参考资料</a><!-- GFM-TOC --></li>
</ul>
<h1 id="一、基础"><a href="#一、基础" class="headerlink" title="一、基础"></a>一、基础</h1><p>模式定义了数据如何存储、存储什么样的数据以及数据如何分解等信息，数据库和表都有模式。</p>
<p>主键的值不允许修改，也不允许复用（不能将已经删除的主键值赋给新数据行的主键）。</p>
<p>SQL（Structured Query Language)，标准 SQL 由 ANSI 标准委员会管理，从而称为 ANSI SQL。各个 DBMS 都有自己的实现，如 PL/SQL、Transact-SQL 等。</p>
<p>SQL 语句不区分大小写，但是数据库表名、列名和值是否区分依赖于具体的 DBMS 以及配置。</p>
<p>SQL 支持以下三种注释：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"># 注释</span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable; <span class="comment">-- 注释</span></span><br><span class="line"><span class="comment">/* 注释1</span></span><br><span class="line"><span class="comment">   注释2 */</span></span><br></pre></td></tr></table></figure>

<p>数据库创建与使用：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> DATABASE test;</span><br><span class="line">USE test;</span><br></pre></td></tr></table></figure>

<h1 id="二、创建表"><a href="#二、创建表" class="headerlink" title="二、创建表"></a>二、创建表</h1><figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> mytable (</span><br><span class="line">  # <span class="type">int</span> 类型，不为空，自增</span><br><span class="line">  id <span class="type">INT</span> <span class="keyword">NOT</span> <span class="keyword">NULL</span> AUTO_INCREMENT,</span><br><span class="line">  # <span class="type">int</span> 类型，不可为空，默认值为 <span class="number">1</span>，不为空</span><br><span class="line">  col1 <span class="type">INT</span> <span class="keyword">NOT</span> <span class="keyword">NULL</span> <span class="keyword">DEFAULT</span> <span class="number">1</span>,</span><br><span class="line">  # 变长字符串类型，最长为 <span class="number">45</span> 个字符，可以为空</span><br><span class="line">  col2 <span class="type">VARCHAR</span>(<span class="number">45</span>) <span class="keyword">NULL</span>,</span><br><span class="line">  # 日期类型，可为空</span><br><span class="line">  col3 <span class="type">DATE</span> <span class="keyword">NULL</span>,</span><br><span class="line">  # 设置主键为 id</span><br><span class="line">  <span class="keyword">PRIMARY</span> KEY (`id`));</span><br></pre></td></tr></table></figure>

<h1 id="三、修改表"><a href="#三、修改表" class="headerlink" title="三、修改表"></a>三、修改表</h1><p>添加列</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> mytable</span><br><span class="line"><span class="keyword">ADD</span> col <span class="type">CHAR</span>(<span class="number">20</span>);</span><br></pre></td></tr></table></figure>

<p>删除列</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">ALTER</span> <span class="keyword">TABLE</span> mytable</span><br><span class="line"><span class="keyword">DROP</span> <span class="keyword">COLUMN</span> col;</span><br></pre></td></tr></table></figure>

<p>删除表</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">TABLE</span> mytable;</span><br></pre></td></tr></table></figure>

<h1 id="四、插入"><a href="#四、插入" class="headerlink" title="四、插入"></a>四、插入</h1><p>普通插入</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> mytable(col1, col2)</span><br><span class="line"><span class="keyword">VALUES</span>(val1, val2);</span><br></pre></td></tr></table></figure>

<p>插入检索出来的数据</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> mytable1(col1, col2)</span><br><span class="line"><span class="keyword">SELECT</span> col1, col2</span><br><span class="line"><span class="keyword">FROM</span> mytable2;</span><br></pre></td></tr></table></figure>

<p>将一个表的内容插入到一个新表</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> newtable <span class="keyword">AS</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> mytable;</span><br></pre></td></tr></table></figure>

<h1 id="五、更新"><a href="#五、更新" class="headerlink" title="五、更新"></a>五、更新</h1><figure class="highlight sql"><table><tr><td class="code"><pre><span class="line">UPDATE mytable</span><br><span class="line"><span class="keyword">SET</span> col <span class="operator">=</span> val</span><br><span class="line"><span class="keyword">WHERE</span> id <span class="operator">=</span> <span class="number">1</span>;</span><br></pre></td></tr></table></figure>

<h1 id="六、删除"><a href="#六、删除" class="headerlink" title="六、删除"></a>六、删除</h1><figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">DELETE</span> <span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> id <span class="operator">=</span> <span class="number">1</span>;</span><br></pre></td></tr></table></figure>

<p><strong>TRUNCATE TABLE</strong>   可以清空表，也就是删除所有行。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">TRUNCATE</span> <span class="keyword">TABLE</span> mytable;</span><br></pre></td></tr></table></figure>

<p>使用更新和删除操作时一定要用 WHERE 子句，不然会把整张表的数据都破坏。可以先用 SELECT 语句进行测试，防止错误删除。</p>
<h1 id="七、查询"><a href="#七、查询" class="headerlink" title="七、查询"></a>七、查询</h1><h2 id="DISTINCT"><a href="#DISTINCT" class="headerlink" title="DISTINCT"></a>DISTINCT</h2><p>相同值只会出现一次。它作用于所有列，也就是说所有列的值都相同才算相同。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="keyword">DISTINCT</span> col1, col2</span><br><span class="line"><span class="keyword">FROM</span> mytable;</span><br></pre></td></tr></table></figure>

<h2 id="LIMIT"><a href="#LIMIT" class="headerlink" title="LIMIT"></a>LIMIT</h2><p>限制返回的行数。可以有两个参数，第一个参数为起始行，从 0 开始；第二个参数为返回的总行数。</p>
<p>返回前 5 行：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line">LIMIT <span class="number">5</span>;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line">LIMIT <span class="number">0</span>, <span class="number">5</span>;</span><br></pre></td></tr></table></figure>

<p>返回第 3 ~ 5 行：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line">LIMIT <span class="number">2</span>, <span class="number">3</span>;</span><br></pre></td></tr></table></figure>

<h1 id="八、排序"><a href="#八、排序" class="headerlink" title="八、排序"></a>八、排序</h1><ul>
<li>  <strong>ASC</strong>  ：升序（默认）</li>
<li>  <strong>DESC</strong>  ：降序</li>
</ul>
<p>可以按多个列进行排序，并且为每个列指定不同的排序方式：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> col1 <span class="keyword">DESC</span>, col2 <span class="keyword">ASC</span>;</span><br></pre></td></tr></table></figure>

<h1 id="九、过滤"><a href="#九、过滤" class="headerlink" title="九、过滤"></a>九、过滤</h1><p>不进行过滤的数据非常大，导致通过网络传输了多余的数据，从而浪费了网络带宽。因此尽量使用 SQL 语句来过滤不必要的数据，而不是传输所有的数据到客户端中然后由客户端进行过滤。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> col <span class="keyword">IS</span> <span class="keyword">NULL</span>;</span><br></pre></td></tr></table></figure>

<p>下表显示了 WHERE 子句可用的操作符</p>
<table>
<thead>
<tr>
<th align="center">操作符</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">=</td>
<td align="center">等于</td>
</tr>
<tr>
<td align="center">&lt;</td>
<td align="center">小于</td>
</tr>
<tr>
<td align="center">&gt;</td>
<td align="center">大于</td>
</tr>
<tr>
<td align="center">&lt;&gt; !=</td>
<td align="center">不等于</td>
</tr>
<tr>
<td align="center">&lt;= !&gt;</td>
<td align="center">小于等于</td>
</tr>
<tr>
<td align="center">&gt;= !&lt;</td>
<td align="center">大于等于</td>
</tr>
<tr>
<td align="center">BETWEEN</td>
<td align="center">在两个值之间</td>
</tr>
<tr>
<td align="center">IS NULL</td>
<td align="center">为 NULL 值</td>
</tr>
</tbody></table>
<p>应该注意到，NULL 与 0、空字符串都不同。</p>
<p><strong>AND 和 OR</strong>   用于连接多个过滤条件。优先处理 AND，当一个过滤表达式涉及到多个 AND 和 OR 时，可以使用 () 来决定优先级，使得优先级关系更清晰。</p>
<p><strong>IN</strong>   操作符用于匹配一组值，其后也可以接一个 SELECT 子句，从而匹配子查询得到的一组值。</p>
<p><strong>NOT</strong>   操作符用于否定一个条件。</p>
<h1 id="十、通配符"><a href="#十、通配符" class="headerlink" title="十、通配符"></a>十、通配符</h1><p>通配符也是用在过滤语句中，但它只能用于文本字段。</p>
<ul>
<li><p>  <strong>%</strong>   匹配 &gt;=0 个任意字符；</p>
</li>
<li><p>  <strong>_</strong>   匹配 ==1 个任意字符；</p>
</li>
<li><p>  <strong>[ ]</strong>   可以匹配集合内的字符，例如 [ab] 将匹配字符 a 或者 b。用脱字符 ^ 可以对其进行否定，也就是不匹配集合内的字符。</p>
</li>
</ul>
<p>使用 Like 来进行通配符匹配。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> col <span class="keyword">LIKE</span> <span class="string">&#x27;[^AB]%&#x27;</span>; <span class="comment">-- 不以 A 和 B 开头的任意文本</span></span><br></pre></td></tr></table></figure>

<p>不要滥用通配符，通配符位于开头处匹配会非常慢。</p>
<h1 id="十一、计算字段"><a href="#十一、计算字段" class="headerlink" title="十一、计算字段"></a>十一、计算字段</h1><p>在数据库服务器上完成数据的转换和格式化的工作往往比客户端上快得多，并且转换和格式化后的数据量更少的话可以减少网络通信量。</p>
<p>计算字段通常需要使用   <strong>AS</strong>   来取别名，否则输出的时候字段名为计算表达式。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> col1 <span class="operator">*</span> col2 <span class="keyword">AS</span> alias</span><br><span class="line"><span class="keyword">FROM</span> mytable;</span><br></pre></td></tr></table></figure>

<p><strong>CONCAT()</strong>   用于连接两个字段。许多数据库会使用空格把一个值填充为列宽，因此连接的结果会出现一些不必要的空格，使用 <strong>TRIM()</strong> 可以去除首尾空格。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> CONCAT(<span class="built_in">TRIM</span>(col1), <span class="string">&#x27;(&#x27;</span>, <span class="built_in">TRIM</span>(col2), <span class="string">&#x27;)&#x27;</span>) <span class="keyword">AS</span> concat_col</span><br><span class="line"><span class="keyword">FROM</span> mytable;</span><br></pre></td></tr></table></figure>

<h1 id="十二、函数"><a href="#十二、函数" class="headerlink" title="十二、函数"></a>十二、函数</h1><p>各个 DBMS 的函数都是不相同的，因此不可移植，以下主要是 MySQL 的函数。</p>
<h2 id="汇总"><a href="#汇总" class="headerlink" title="汇总"></a>汇总</h2><table>
<thead>
<tr>
<th align="center">函 数</th>
<th align="center">说 明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">AVG()</td>
<td align="center">返回某列的平均值</td>
</tr>
<tr>
<td align="center">COUNT()</td>
<td align="center">返回某列的行数</td>
</tr>
<tr>
<td align="center">MAX()</td>
<td align="center">返回某列的最大值</td>
</tr>
<tr>
<td align="center">MIN()</td>
<td align="center">返回某列的最小值</td>
</tr>
<tr>
<td align="center">SUM()</td>
<td align="center">返回某列值之和</td>
</tr>
</tbody></table>
<p>AVG() 会忽略 NULL 行。</p>
<p>使用 DISTINCT 可以汇总不同的值。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="built_in">AVG</span>(<span class="keyword">DISTINCT</span> col1) <span class="keyword">AS</span> avg_col</span><br><span class="line"><span class="keyword">FROM</span> mytable;</span><br></pre></td></tr></table></figure>

<h2 id="文本处理"><a href="#文本处理" class="headerlink" title="文本处理"></a>文本处理</h2><table>
<thead>
<tr>
<th align="center">函数</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">LEFT()</td>
<td align="center">左边的字符</td>
</tr>
<tr>
<td align="center">RIGHT()</td>
<td align="center">右边的字符</td>
</tr>
<tr>
<td align="center">LOWER()</td>
<td align="center">转换为小写字符</td>
</tr>
<tr>
<td align="center">UPPER()</td>
<td align="center">转换为大写字符</td>
</tr>
<tr>
<td align="center">LTRIM()</td>
<td align="center">去除左边的空格</td>
</tr>
<tr>
<td align="center">RTRIM()</td>
<td align="center">去除右边的空格</td>
</tr>
<tr>
<td align="center">LENGTH()</td>
<td align="center">长度</td>
</tr>
<tr>
<td align="center">SOUNDEX()</td>
<td align="center">转换为语音值</td>
</tr>
</tbody></table>
<p>其中，  <strong>SOUNDEX()</strong>   可以将一个字符串转换为描述其语音表示的字母数字模式。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> SOUNDEX(col1) <span class="operator">=</span> SOUNDEX(<span class="string">&#x27;apple&#x27;</span>)</span><br></pre></td></tr></table></figure>

<h2 id="日期和时间处理"><a href="#日期和时间处理" class="headerlink" title="日期和时间处理"></a>日期和时间处理</h2><ul>
<li>日期格式：YYYY-MM-DD</li>
<li>时间格式：HH:&lt;zero-width space&gt;MM:SS</li>
</ul>
<table>
<thead>
<tr>
<th align="center">函 数</th>
<th align="center">说 明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">ADDDATE()</td>
<td align="center">增加一个日期（天、周等）</td>
</tr>
<tr>
<td align="center">ADDTIME()</td>
<td align="center">增加一个时间（时、分等）</td>
</tr>
<tr>
<td align="center">CURDATE()</td>
<td align="center">返回当前日期</td>
</tr>
<tr>
<td align="center">CURTIME()</td>
<td align="center">返回当前时间</td>
</tr>
<tr>
<td align="center">DATE()</td>
<td align="center">返回日期时间的日期部分</td>
</tr>
<tr>
<td align="center">DATEDIFF()</td>
<td align="center">计算两个日期之差</td>
</tr>
<tr>
<td align="center">DATE_ADD()</td>
<td align="center">高度灵活的日期运算函数</td>
</tr>
<tr>
<td align="center">DATE_FORMAT()</td>
<td align="center">返回一个格式化的日期或时间串</td>
</tr>
<tr>
<td align="center">DAY()</td>
<td align="center">返回一个日期的天数部分</td>
</tr>
<tr>
<td align="center">DAYOFWEEK()</td>
<td align="center">对于一个日期，返回对应的星期几</td>
</tr>
<tr>
<td align="center">HOUR()</td>
<td align="center">返回一个时间的小时部分</td>
</tr>
<tr>
<td align="center">MINUTE()</td>
<td align="center">返回一个时间的分钟部分</td>
</tr>
<tr>
<td align="center">MONTH()</td>
<td align="center">返回一个日期的月份部分</td>
</tr>
<tr>
<td align="center">NOW()</td>
<td align="center">返回当前日期和时间</td>
</tr>
<tr>
<td align="center">SECOND()</td>
<td align="center">返回一个时间的秒部分</td>
</tr>
<tr>
<td align="center">TIME()</td>
<td align="center">返回一个日期时间的时间部分</td>
</tr>
<tr>
<td align="center">YEAR()</td>
<td align="center">返回一个日期的年份部分</td>
</tr>
</tbody></table>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line">mysql<span class="operator">&gt;</span> <span class="keyword">SELECT</span> NOW();</span><br></pre></td></tr></table></figure>

<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">2018-4-14 20:25:11</span><br></pre></td></tr></table></figure>

<h2 id="数值处理"><a href="#数值处理" class="headerlink" title="数值处理"></a>数值处理</h2><table>
<thead>
<tr>
<th align="center">函数</th>
<th align="center">说明</th>
</tr>
</thead>
<tbody><tr>
<td align="center">SIN()</td>
<td align="center">正弦</td>
</tr>
<tr>
<td align="center">COS()</td>
<td align="center">余弦</td>
</tr>
<tr>
<td align="center">TAN()</td>
<td align="center">正切</td>
</tr>
<tr>
<td align="center">ABS()</td>
<td align="center">绝对值</td>
</tr>
<tr>
<td align="center">SQRT()</td>
<td align="center">平方根</td>
</tr>
<tr>
<td align="center">MOD()</td>
<td align="center">余数</td>
</tr>
<tr>
<td align="center">EXP()</td>
<td align="center">指数</td>
</tr>
<tr>
<td align="center">PI()</td>
<td align="center">圆周率</td>
</tr>
<tr>
<td align="center">RAND()</td>
<td align="center">随机数</td>
</tr>
</tbody></table>
<h1 id="十三、分组"><a href="#十三、分组" class="headerlink" title="十三、分组"></a>十三、分组</h1><p>把具有相同的数据值的行放在同一组中。</p>
<p>可以对同一分组数据使用汇总函数进行处理，例如求分组数据的平均值等。</p>
<p>指定的分组字段除了能按该字段进行分组，也会自动按该字段进行排序。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> col, <span class="built_in">COUNT</span>(<span class="operator">*</span>) <span class="keyword">AS</span> num</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">GROUP</span> <span class="keyword">BY</span> col;</span><br></pre></td></tr></table></figure>

<p>GROUP BY 自动按分组字段进行排序，ORDER BY 也可以按汇总字段来进行排序。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> col, <span class="built_in">COUNT</span>(<span class="operator">*</span>) <span class="keyword">AS</span> num</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">GROUP</span> <span class="keyword">BY</span> col</span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> num;</span><br></pre></td></tr></table></figure>

<p>WHERE 过滤行，HAVING 过滤分组，行过滤应当先于分组过滤。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> col, <span class="built_in">COUNT</span>(<span class="operator">*</span>) <span class="keyword">AS</span> num</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> col <span class="operator">&gt;</span> <span class="number">2</span></span><br><span class="line"><span class="keyword">GROUP</span> <span class="keyword">BY</span> col</span><br><span class="line"><span class="keyword">HAVING</span> num <span class="operator">&gt;=</span> <span class="number">2</span>;</span><br></pre></td></tr></table></figure>

<p>分组规定：</p>
<ul>
<li>GROUP BY 子句出现在 WHERE 子句之后，ORDER BY 子句之前；</li>
<li>除了汇总字段外，SELECT 语句中的每一字段都必须在 GROUP BY 子句中给出；</li>
<li>NULL 的行会单独分为一组；</li>
<li>大多数 SQL 实现不支持 GROUP BY 列具有可变长度的数据类型。</li>
</ul>
<h1 id="十四、子查询"><a href="#十四、子查询" class="headerlink" title="十四、子查询"></a>十四、子查询</h1><p>子查询中只能返回一个字段的数据。</p>
<p>可以将子查询的结果作为 WHRER 语句的过滤条件：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable1</span><br><span class="line"><span class="keyword">WHERE</span> col1 <span class="keyword">IN</span> (<span class="keyword">SELECT</span> col2</span><br><span class="line">               <span class="keyword">FROM</span> mytable2);</span><br></pre></td></tr></table></figure>

<p>下面的语句可以检索出客户的订单数量，子查询语句会对第一个查询检索出的每个客户执行一次：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> cust_name, (<span class="keyword">SELECT</span> <span class="built_in">COUNT</span>(<span class="operator">*</span>)</span><br><span class="line">                   <span class="keyword">FROM</span> Orders</span><br><span class="line">                   <span class="keyword">WHERE</span> Orders.cust_id <span class="operator">=</span> Customers.cust_id)</span><br><span class="line">                   <span class="keyword">AS</span> orders_num</span><br><span class="line"><span class="keyword">FROM</span> Customers</span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> cust_name;</span><br></pre></td></tr></table></figure>

<h1 id="十五、连接"><a href="#十五、连接" class="headerlink" title="十五、连接"></a>十五、连接</h1><p>连接用于连接多个表，使用 JOIN 关键字，并且条件语句使用 ON 而不是 WHERE。</p>
<p>连接可以替换子查询，并且比子查询的效率一般会更快。</p>
<p>可以用 AS 给列名、计算字段和表名取别名，给表名取别名是为了简化 SQL 语句以及连接相同表。</p>
<h2 id="内连接"><a href="#内连接" class="headerlink" title="内连接"></a>内连接</h2><p>内连接又称等值连接，使用 INNER JOIN 关键字。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> A.value, B.value</span><br><span class="line"><span class="keyword">FROM</span> tablea <span class="keyword">AS</span> A <span class="keyword">INNER</span> <span class="keyword">JOIN</span> tableb <span class="keyword">AS</span> B</span><br><span class="line"><span class="keyword">ON</span> A.key <span class="operator">=</span> B.key;</span><br></pre></td></tr></table></figure>

<p>可以不明确使用 INNER JOIN，而使用普通查询并在 WHERE 中将两个表中要连接的列用等值方法连接起来。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> A.value, B.value</span><br><span class="line"><span class="keyword">FROM</span> tablea <span class="keyword">AS</span> A, tableb <span class="keyword">AS</span> B</span><br><span class="line"><span class="keyword">WHERE</span> A.key <span class="operator">=</span> B.key;</span><br></pre></td></tr></table></figure>

<h2 id="自连接"><a href="#自连接" class="headerlink" title="自连接"></a>自连接</h2><p>自连接可以看成内连接的一种，只是连接的表是自身而已。</p>
<p>一张员工表，包含员工姓名和员工所属部门，要找出与 Jim 处在同一部门的所有员工姓名。</p>
<p>子查询版本</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> name</span><br><span class="line"><span class="keyword">FROM</span> employee</span><br><span class="line"><span class="keyword">WHERE</span> department <span class="operator">=</span> (</span><br><span class="line">      <span class="keyword">SELECT</span> department</span><br><span class="line">      <span class="keyword">FROM</span> employee</span><br><span class="line">      <span class="keyword">WHERE</span> name <span class="operator">=</span> &quot;Jim&quot;);</span><br></pre></td></tr></table></figure>

<p>自连接版本</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> e1.name</span><br><span class="line"><span class="keyword">FROM</span> employee <span class="keyword">AS</span> e1 <span class="keyword">INNER</span> <span class="keyword">JOIN</span> employee <span class="keyword">AS</span> e2</span><br><span class="line"><span class="keyword">ON</span> e1.department <span class="operator">=</span> e2.department</span><br><span class="line">      <span class="keyword">AND</span> e2.name <span class="operator">=</span> &quot;Jim&quot;;</span><br></pre></td></tr></table></figure>

<h2 id="自然连接"><a href="#自然连接" class="headerlink" title="自然连接"></a>自然连接</h2><p>自然连接是把同名列通过等值测试连接起来的，同名列可以有多个。</p>
<p>内连接和自然连接的区别：内连接提供连接的列，而自然连接自动连接所有同名列。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> A.value, B.value</span><br><span class="line"><span class="keyword">FROM</span> tablea <span class="keyword">AS</span> A <span class="keyword">NATURAL</span> <span class="keyword">JOIN</span> tableb <span class="keyword">AS</span> B;</span><br></pre></td></tr></table></figure>

<h2 id="外连接"><a href="#外连接" class="headerlink" title="外连接"></a>外连接</h2><p>外连接保留了没有关联的那些行。分为左外连接，右外连接以及全外连接，左外连接就是保留左表没有关联的行。</p>
<p>检索所有顾客的订单信息，包括还没有订单信息的顾客。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> Customers.cust_id, Customer.cust_name, Orders.order_id</span><br><span class="line"><span class="keyword">FROM</span> Customers <span class="keyword">LEFT</span> <span class="keyword">OUTER</span> <span class="keyword">JOIN</span> Orders</span><br><span class="line"><span class="keyword">ON</span> Customers.cust_id <span class="operator">=</span> Orders.cust_id;</span><br></pre></td></tr></table></figure>

<p>customers 表：</p>
<table>
<thead>
<tr>
<th align="center">cust_id</th>
<th align="center">cust_name</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">a</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">b</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">c</td>
</tr>
</tbody></table>
<p>orders 表：</p>
<table>
<thead>
<tr>
<th align="center">order_id</th>
<th align="center">cust_id</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">1</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">1</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">3</td>
</tr>
<tr>
<td align="center">4</td>
<td align="center">3</td>
</tr>
</tbody></table>
<p>结果：</p>
<table>
<thead>
<tr>
<th align="center">cust_id</th>
<th align="center">cust_name</th>
<th align="center">order_id</th>
</tr>
</thead>
<tbody><tr>
<td align="center">1</td>
<td align="center">a</td>
<td align="center">1</td>
</tr>
<tr>
<td align="center">1</td>
<td align="center">a</td>
<td align="center">2</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">c</td>
<td align="center">3</td>
</tr>
<tr>
<td align="center">3</td>
<td align="center">c</td>
<td align="center">4</td>
</tr>
<tr>
<td align="center">2</td>
<td align="center">b</td>
<td align="center">Null</td>
</tr>
</tbody></table>
<h1 id="十六、组合查询"><a href="#十六、组合查询" class="headerlink" title="十六、组合查询"></a>十六、组合查询</h1><p>使用   <strong>UNION</strong>   来组合两个查询，如果第一个查询返回 M 行，第二个查询返回 N 行，那么组合查询的结果一般为 M+N 行。</p>
<p>每个查询必须包含相同的列、表达式和聚集函数。</p>
<p>默认会去除相同行，如果需要保留相同行，使用 UNION ALL。</p>
<p>只能包含一个 ORDER BY 子句，并且必须位于语句的最后。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> col</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> col <span class="operator">=</span> <span class="number">1</span></span><br><span class="line"><span class="keyword">UNION</span></span><br><span class="line"><span class="keyword">SELECT</span> col</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> col <span class="operator">=</span><span class="number">2</span>;</span><br></pre></td></tr></table></figure>

<h1 id="十七、视图"><a href="#十七、视图" class="headerlink" title="十七、视图"></a>十七、视图</h1><p>视图是虚拟的表，本身不包含数据，也就不能对其进行索引操作。</p>
<p>对视图的操作和对普通表的操作一样。</p>
<p>视图具有如下好处：</p>
<ul>
<li>简化复杂的 SQL 操作，比如复杂的连接；</li>
<li>只使用实际表的一部分数据；</li>
<li>通过只给用户访问视图的权限，保证数据的安全性；</li>
<li>更改数据格式和表示。</li>
</ul>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">VIEW</span> myview <span class="keyword">AS</span></span><br><span class="line"><span class="keyword">SELECT</span> Concat(col1, col2) <span class="keyword">AS</span> concat_col, col3<span class="operator">*</span>col4 <span class="keyword">AS</span> compute_col</span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">WHERE</span> col5 <span class="operator">=</span> val;</span><br></pre></td></tr></table></figure>

<h1 id="十八、存储过程"><a href="#十八、存储过程" class="headerlink" title="十八、存储过程"></a>十八、存储过程</h1><p>存储过程可以看成是对一系列 SQL 操作的批处理。</p>
<p>使用存储过程的好处：</p>
<ul>
<li>代码封装，保证了一定的安全性；</li>
<li>代码复用；</li>
<li>由于是预先编译，因此具有很高的性能。</li>
</ul>
<p>命令行中创建存储过程需要自定义分隔符，因为命令行是以 ; 为结束符，而存储过程中也包含了分号，因此会错误把这部分分号当成是结束符，造成语法错误。</p>
<p>包含 in、out 和 inout 三种参数。</p>
<p>给变量赋值都需要用 select into 语句。</p>
<p>每次只能给一个变量赋值，不支持集合的操作。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line">delimiter <span class="operator">/</span><span class="operator">/</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">procedure</span> myprocedure( <span class="keyword">out</span> ret <span class="type">int</span> )</span><br><span class="line">    <span class="keyword">begin</span></span><br><span class="line">        <span class="keyword">declare</span> y <span class="type">int</span>;</span><br><span class="line">        <span class="keyword">select</span> <span class="built_in">sum</span>(col1)</span><br><span class="line">        <span class="keyword">from</span> mytable</span><br><span class="line">        <span class="keyword">into</span> y;</span><br><span class="line">        <span class="keyword">select</span> y<span class="operator">*</span>y <span class="keyword">into</span> ret;</span><br><span class="line">    <span class="keyword">end</span> <span class="operator">/</span><span class="operator">/</span></span><br><span class="line"></span><br><span class="line">delimiter ;</span><br></pre></td></tr></table></figure>

<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">call</span> myprocedure(<span class="variable">@ret</span>);</span><br><span class="line"><span class="keyword">select</span> <span class="variable">@ret</span>;</span><br></pre></td></tr></table></figure>

<h1 id="十九、游标"><a href="#十九、游标" class="headerlink" title="十九、游标"></a>十九、游标</h1><p>在存储过程中使用游标可以对一个结果集进行移动遍历。</p>
<p>游标主要用于交互式应用，其中用户需要对数据集中的任意行进行浏览和修改。</p>
<p>使用游标的四个步骤：</p>
<ol>
<li>声明游标，这个过程没有实际检索出数据；</li>
<li>打开游标；</li>
<li>取出数据；</li>
<li>关闭游标；</li>
</ol>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line">delimiter <span class="operator">/</span><span class="operator">/</span></span><br><span class="line"><span class="keyword">create</span> <span class="keyword">procedure</span> myprocedure(<span class="keyword">out</span> ret <span class="type">int</span>)</span><br><span class="line">    <span class="keyword">begin</span></span><br><span class="line">        <span class="keyword">declare</span> done <span class="type">boolean</span> <span class="keyword">default</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">declare</span> mycursor <span class="keyword">cursor</span> <span class="keyword">for</span></span><br><span class="line">        <span class="keyword">select</span> col1 <span class="keyword">from</span> mytable;</span><br><span class="line">        # 定义了一个 continue handler，当 <span class="keyword">sqlstate</span> <span class="string">&#x27;02000&#x27;</span> 这个条件出现时，会执行 <span class="keyword">set</span> done <span class="operator">=</span> <span class="number">1</span></span><br><span class="line">        <span class="keyword">declare</span> continue handler <span class="keyword">for</span> <span class="keyword">sqlstate</span> <span class="string">&#x27;02000&#x27;</span> <span class="keyword">set</span> done <span class="operator">=</span> <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">open</span> mycursor;</span><br><span class="line"></span><br><span class="line">        repeat</span><br><span class="line">            <span class="keyword">fetch</span> mycursor <span class="keyword">into</span> ret;</span><br><span class="line">            <span class="keyword">select</span> ret;</span><br><span class="line">        until done <span class="keyword">end</span> repeat;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">close</span> mycursor;</span><br><span class="line">    <span class="keyword">end</span> <span class="operator">/</span><span class="operator">/</span></span><br><span class="line"> delimiter ;</span><br></pre></td></tr></table></figure>

<h1 id="二十、触发器"><a href="#二十、触发器" class="headerlink" title="二十、触发器"></a>二十、触发器</h1><p>触发器会在某个表执行以下语句时而自动执行：DELETE、INSERT、UPDATE。</p>
<p>触发器必须指定在语句执行之前还是之后自动执行，之前执行使用 BEFORE 关键字，之后执行使用 AFTER 关键字。BEFORE 用于数据验证和净化，AFTER 用于审计跟踪，将修改记录到另外一张表中。</p>
<p>INSERT 触发器包含一个名为 NEW 的虚拟表。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TRIGGER</span> mytrigger AFTER <span class="keyword">INSERT</span> <span class="keyword">ON</span> mytable</span><br><span class="line"><span class="keyword">FOR</span> <span class="keyword">EACH</span> <span class="type">ROW</span> <span class="keyword">SELECT</span> NEW.col <span class="keyword">into</span> <span class="variable">@result</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">SELECT</span> <span class="variable">@result</span>; <span class="comment">-- 获取结果</span></span><br></pre></td></tr></table></figure>

<p>DELETE 触发器包含一个名为 OLD 的虚拟表，并且是只读的。</p>
<p>UPDATE 触发器包含一个名为 NEW 和一个名为 OLD 的虚拟表，其中 NEW 是可以被修改的，而 OLD 是只读的。</p>
<p>MySQL 不允许在触发器中使用 CALL 语句，也就是不能调用存储过程。</p>
<h1 id="二十一、事务管理"><a href="#二十一、事务管理" class="headerlink" title="二十一、事务管理"></a>二十一、事务管理</h1><p>基本术语：</p>
<ul>
<li>事务（transaction）指一组 SQL 语句；</li>
<li>回退（rollback）指撤销指定 SQL 语句的过程；</li>
<li>提交（commit）指将未存储的 SQL 语句结果写入数据库表；</li>
<li>保留点（savepoint）指事务处理中设置的临时占位符（placeholder），你可以对它发布回退（与回退整个事务处理不同）。</li>
</ul>
<p>不能回退 SELECT 语句，回退 SELECT 语句也没意义；也不能回退 CREATE 和 DROP 语句。</p>
<p>MySQL 的事务提交默认是隐式提交，每执行一条语句就把这条语句当成一个事务然后进行提交。当出现 START TRANSACTION 语句时，会关闭隐式提交；当 COMMIT 或 ROLLBACK 语句执行后，事务会自动关闭，重新恢复隐式提交。</p>
<p>设置 autocommit 为 0 可以取消自动提交；autocommit 标记是针对每个连接而不是针对服务器的。</p>
<p>如果没有设置保留点，ROLLBACK 会回退到 START TRANSACTION 语句处；如果设置了保留点，并且在 ROLLBACK 中指定该保留点，则会回退到该保留点。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">START</span> TRANSACTION</span><br><span class="line"><span class="operator">/</span><span class="operator">/</span> ...</span><br><span class="line"><span class="keyword">SAVEPOINT</span> delete1</span><br><span class="line"><span class="operator">/</span><span class="operator">/</span> ...</span><br><span class="line"><span class="keyword">ROLLBACK</span> <span class="keyword">TO</span> delete1</span><br><span class="line"><span class="operator">/</span><span class="operator">/</span> ...</span><br><span class="line"><span class="keyword">COMMIT</span></span><br></pre></td></tr></table></figure>

<h1 id="二十二、字符集"><a href="#二十二、字符集" class="headerlink" title="二十二、字符集"></a>二十二、字符集</h1><p>基本术语：</p>
<ul>
<li>字符集为字母和符号的集合；</li>
<li>编码为某个字符集成员的内部表示；</li>
<li>校对字符指定如何比较，主要用于排序和分组。</li>
</ul>
<p>除了给表指定字符集和校对外，也可以给列指定：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> mytable</span><br><span class="line">(col <span class="type">VARCHAR</span>(<span class="number">10</span>) <span class="type">CHARACTER</span> <span class="keyword">SET</span> latin <span class="keyword">COLLATE</span> latin1_general_ci )</span><br><span class="line"><span class="keyword">DEFAULT</span> <span class="type">CHARACTER</span> <span class="keyword">SET</span> hebrew <span class="keyword">COLLATE</span> hebrew_general_ci;</span><br></pre></td></tr></table></figure>

<p>可以在排序、分组时指定校对：</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span></span><br><span class="line"><span class="keyword">FROM</span> mytable</span><br><span class="line"><span class="keyword">ORDER</span> <span class="keyword">BY</span> col <span class="keyword">COLLATE</span> latin1_general_ci;</span><br></pre></td></tr></table></figure>

<h1 id="二十三、权限管理"><a href="#二十三、权限管理" class="headerlink" title="二十三、权限管理"></a>二十三、权限管理</h1><p>MySQL 的账户信息保存在 mysql 这个数据库中。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line">USE mysql;</span><br><span class="line"><span class="keyword">SELECT</span> <span class="keyword">user</span> <span class="keyword">FROM</span> <span class="keyword">user</span>;</span><br></pre></td></tr></table></figure>

<p><strong>创建账户</strong>  </p>
<p>新创建的账户没有任何权限。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">USER</span> myuser IDENTIFIED <span class="keyword">BY</span> <span class="string">&#x27;mypassword&#x27;</span>;</span><br></pre></td></tr></table></figure>

<p><strong>修改账户名</strong>  </p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line">RENAME <span class="keyword">USER</span> myuser <span class="keyword">TO</span> newuser;</span><br></pre></td></tr></table></figure>

<p><strong>删除账户</strong>  </p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">DROP</span> <span class="keyword">USER</span> myuser;</span><br></pre></td></tr></table></figure>

<p><strong>查看权限</strong>  </p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SHOW</span> GRANTS <span class="keyword">FOR</span> myuser;</span><br></pre></td></tr></table></figure>

<p><strong>授予权限</strong>  </p>
<p>账户用 username@host 的形式定义，username@% 使用的是默认主机名。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">GRANT</span> <span class="keyword">SELECT</span>, <span class="keyword">INSERT</span> <span class="keyword">ON</span> mydatabase.<span class="operator">*</span> <span class="keyword">TO</span> myuser;</span><br></pre></td></tr></table></figure>

<p><strong>删除权限</strong>  </p>
<p>GRANT 和 REVOKE 可在几个层次上控制访问权限：</p>
<ul>
<li>整个服务器，使用 GRANT ALL 和 REVOKE ALL；</li>
<li>整个数据库，使用 ON database.*；</li>
<li>特定的表，使用 ON database.table；</li>
<li>特定的列；</li>
<li>特定的存储过程。</li>
</ul>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">REVOKE</span> <span class="keyword">SELECT</span>, <span class="keyword">INSERT</span> <span class="keyword">ON</span> mydatabase.<span class="operator">*</span> <span class="keyword">FROM</span> myuser;</span><br></pre></td></tr></table></figure>

<p><strong>更改密码</strong>  </p>
<p>必须使用 Password() 函数进行加密。</p>
<figure class="highlight sql"><table><tr><td class="code"><pre><span class="line"><span class="keyword">SET</span> PASSWROD <span class="keyword">FOR</span> myuser <span class="operator">=</span> Password(<span class="string">&#x27;new_password&#x27;</span>);</span><br></pre></td></tr></table></figure>

<h1 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h1><ul>
<li>BenForta. SQL 必知必会 [M]. 人民邮电出版社, 2013.</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Zhang Shuo</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/SQL/">https://zhang-shuo-fr.gitee.io/hexo3/2021/12/06/notes/SQL/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhang-shuo-fr.gitee.io/hexo3" target="_blank">Zhang Shuo'blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/hexo3/tags/SQL/">SQL</a></div><div class="post_share"><div class="social-share" data-image="/hexo3/img/20.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/hexo3/img/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/hexo3/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/hexo3/img/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/hexo3/2021/12/06/notes/%E6%95%B0%E6%8D%AE%E5%BA%93%E7%B3%BB%E7%BB%9F%E5%8E%9F%E7%90%86/"><img class="prev-cover" src= "" data-lazy-src="/hexo3/img/13.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">数据库系统原理</div></div></a></div><div class="next-post pull-right"><a href="/hexo3/2021/12/06/notes/SQL%20%E8%AF%AD%E6%B3%95/"><img class="next-cover" src= "" data-lazy-src="/hexo3/img/13.jpg" onerror="onerror=null;src='/hexo3/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">SQL语法</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%9F%BA%E7%A1%80"><span class="toc-number">1.</span> <span class="toc-text">一、基础</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E3%80%81%E5%88%9B%E5%BB%BA%E8%A1%A8"><span class="toc-number">2.</span> <span class="toc-text">二、创建表</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%89%E3%80%81%E4%BF%AE%E6%94%B9%E8%A1%A8"><span class="toc-number">3.</span> <span class="toc-text">三、修改表</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9B%9B%E3%80%81%E6%8F%92%E5%85%A5"><span class="toc-number">4.</span> <span class="toc-text">四、插入</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%94%E3%80%81%E6%9B%B4%E6%96%B0"><span class="toc-number">5.</span> <span class="toc-text">五、更新</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AD%E3%80%81%E5%88%A0%E9%99%A4"><span class="toc-number">6.</span> <span class="toc-text">六、删除</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%83%E3%80%81%E6%9F%A5%E8%AF%A2"><span class="toc-number">7.</span> <span class="toc-text">七、查询</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#DISTINCT"><span class="toc-number">7.1.</span> <span class="toc-text">DISTINCT</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#LIMIT"><span class="toc-number">7.2.</span> <span class="toc-text">LIMIT</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%85%AB%E3%80%81%E6%8E%92%E5%BA%8F"><span class="toc-number">8.</span> <span class="toc-text">八、排序</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B9%9D%E3%80%81%E8%BF%87%E6%BB%A4"><span class="toc-number">9.</span> <span class="toc-text">九、过滤</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E3%80%81%E9%80%9A%E9%85%8D%E7%AC%A6"><span class="toc-number">10.</span> <span class="toc-text">十、通配符</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E4%B8%80%E3%80%81%E8%AE%A1%E7%AE%97%E5%AD%97%E6%AE%B5"><span class="toc-number">11.</span> <span class="toc-text">十一、计算字段</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E4%BA%8C%E3%80%81%E5%87%BD%E6%95%B0"><span class="toc-number">12.</span> <span class="toc-text">十二、函数</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B1%87%E6%80%BB"><span class="toc-number">12.1.</span> <span class="toc-text">汇总</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%87%E6%9C%AC%E5%A4%84%E7%90%86"><span class="toc-number">12.2.</span> <span class="toc-text">文本处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%97%A5%E6%9C%9F%E5%92%8C%E6%97%B6%E9%97%B4%E5%A4%84%E7%90%86"><span class="toc-number">12.3.</span> <span class="toc-text">日期和时间处理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%95%B0%E5%80%BC%E5%A4%84%E7%90%86"><span class="toc-number">12.4.</span> <span class="toc-text">数值处理</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E4%B8%89%E3%80%81%E5%88%86%E7%BB%84"><span class="toc-number">13.</span> <span class="toc-text">十三、分组</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E5%9B%9B%E3%80%81%E5%AD%90%E6%9F%A5%E8%AF%A2"><span class="toc-number">14.</span> <span class="toc-text">十四、子查询</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E4%BA%94%E3%80%81%E8%BF%9E%E6%8E%A5"><span class="toc-number">15.</span> <span class="toc-text">十五、连接</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%85%E8%BF%9E%E6%8E%A5"><span class="toc-number">15.1.</span> <span class="toc-text">内连接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E8%BF%9E%E6%8E%A5"><span class="toc-number">15.2.</span> <span class="toc-text">自连接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%87%AA%E7%84%B6%E8%BF%9E%E6%8E%A5"><span class="toc-number">15.3.</span> <span class="toc-text">自然连接</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A4%96%E8%BF%9E%E6%8E%A5"><span class="toc-number">15.4.</span> <span class="toc-text">外连接</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E5%85%AD%E3%80%81%E7%BB%84%E5%90%88%E6%9F%A5%E8%AF%A2"><span class="toc-number">16.</span> <span class="toc-text">十六、组合查询</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E4%B8%83%E3%80%81%E8%A7%86%E5%9B%BE"><span class="toc-number">17.</span> <span class="toc-text">十七、视图</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E5%85%AB%E3%80%81%E5%AD%98%E5%82%A8%E8%BF%87%E7%A8%8B"><span class="toc-number">18.</span> <span class="toc-text">十八、存储过程</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8D%81%E4%B9%9D%E3%80%81%E6%B8%B8%E6%A0%87"><span class="toc-number">19.</span> <span class="toc-text">十九、游标</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E5%8D%81%E3%80%81%E8%A7%A6%E5%8F%91%E5%99%A8"><span class="toc-number">20.</span> <span class="toc-text">二十、触发器</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E5%8D%81%E4%B8%80%E3%80%81%E4%BA%8B%E5%8A%A1%E7%AE%A1%E7%90%86"><span class="toc-number">21.</span> <span class="toc-text">二十一、事务管理</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E5%8D%81%E4%BA%8C%E3%80%81%E5%AD%97%E7%AC%A6%E9%9B%86"><span class="toc-number">22.</span> <span class="toc-text">二十二、字符集</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BA%8C%E5%8D%81%E4%B8%89%E3%80%81%E6%9D%83%E9%99%90%E7%AE%A1%E7%90%86"><span class="toc-number">23.</span> <span class="toc-text">二十三、权限管理</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="toc-number">24.</span> <span class="toc-text">参考资料</span></a></li></ol></div></div></div></div></main><footer id="footer" style="background-image: url('/hexo3/img/20.jpg')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By Zhang Shuo</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">簡</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/hexo3/js/utils.js"></script><script src="/hexo3/js/main.js"></script><script src="/hexo3/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/hexo3/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><div class="aplayer no-destroy" data-id="000PeZCQ1i4XVs" data-server="tencent" data-type="artist" data-fixed="true" data-mini="true" data-listFolded="false" data-order="random" data-preload="none" data-autoplay="true" muted></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="true"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/aplayer/dist/APlayer.min.js"></script><script src="https://cdn.jsdelivr.net/gh/metowolf/MetingJS@1.2/dist/Meting.min.js"></script><script src="https://cdn.jsdelivr.net/npm/pjax/pjax.min.js"></script><script>let pjaxSelectors = [
  'title',
  '#config-diff',
  '#body-wrap',
  '#rightside-config-hide',
  '#rightside-config-show',
  '.js-pjax'
]

if (false) {
  pjaxSelectors.unshift('meta[property="og:image"]', 'meta[property="og:title"]', 'meta[property="og:url"]')
}

var pjax = new Pjax({
  elements: 'a:not([target="_blank"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.removeEventListener('scroll', window.tocScrollFn)
  window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // Analytics
  if (false) {
    MtaH5.pgv()
  }

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>